/*
 * puerta.cpp
 *
 */
#include <unistd.h>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <exception>
#include "Argv.h"
#include "logger/logger.h"
#include "StringUtils.h"
#include "ProcessAux.h"
#include "API/Puerta.h"
#include "Middleware/IPCCommunicationService.h"
#include "Middleware/MiddlewareMessages.h"

int main(int argc, char **argv)
{
    Argv arguments;
    PuertaId puertaId;

    arguments.setArgv(argv);

    puertaId = StringUtils::StringToNumber<int>(arguments.getArg(1));

    std::stringstream ss;
    ss<<"Puerta "<< puertaId;


	CLogger::create(ss.str());
	CLogger::setLevel(LogLevelEnum::DEBUG);

	try{

		pid_t pid = fork();

		if(pid == 0)
		{
			API::Puerta puerta(API::Puerta::IN_DOOR);

			CLogger::log("Puerta entrada started.",LogLevelEnum::INFO);

			puerta.run(puertaId);

			CLogger::log("Puerta entrada ended.",LogLevelEnum::INFO);

			wait();
		}
		else
		{
			API::Puerta puerta(API::Puerta::OUT_DOOR);

			CLogger::log("Puerta salida started.",LogLevelEnum::INFO);

			puerta.run(puertaId);

			CLogger::log("Puerta salida ended.",LogLevelEnum::INFO);
		}
	}
	catch (std::exception &e)
	{
		CLogger::log(e.what(),LogLevelEnum::FATAL);
	}
	return 0;
}
